#include <QStandardPaths>
#include <iostream>

#include <main_process/mainProcess.h>
#include <utils/config.h>
#include <login_and_registration/logindialog.h>
#include <main_window/mainwindow.h>
#include <users/userslist.h>

namespace main_process{
MainProcess::MainProcess(QApplication &app) : _app(app) { }

int MainProcess::run() {
	try {
		utils::config  config(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation).toStdString());
		users::usersList list(config.usersFile);
		QScopedPointer loginDialog(new login_and_registration::LoginDialog(list));
		main_window::MainWindow w(config);
		users::user user;
		login_and_registration::LoginDialog::connect(loginDialog.data(), &login_and_registration::LoginDialog::acceptLogin,
		                                             &w, &main_window::MainWindow::setUser);
		if(auto code = loginDialog->exec();code == 1) {
			w.show();
			list.saveInFile(config.usersFile);
			return _app.exec();
		}
		list.saveInFile(config.usersFile);
	}
	catch (std::exception& e) {
		std::cerr << "Exception: " << e.what() << std::endl;
		return 1;
	}
	return 0;
}
}